<template>
  <div class="create-product flex-column h-100P">
    <query-container @search="handleSearch" @reset="handleReset">
      <div class="flex align-start">
        <el-form ref="form" :model="formData" inline>
          <el-form-item label="选择物模型" prop="metadataId">
            <selectMetadata
              :metadata-id="formData.metadataId"
              @change="metadataId=>formData.metadataId = metadataId"
            />
          </el-form-item>
          <el-form-item label="发布状态" prop="publishState">
            <el-select v-model="formData.publishStateEnum">
              <el-option
                v-for="item in publishStateEnum"
                :value="item.value"
                :key="item.value"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="keyword" label="关键词">
            <el-input
              v-model="formData.keyword"
              placeholder="请输入产品名称或ID"
              clearable
              suffix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
      </div>
    </query-container>
    <div class="content flex-sub flex-column">
      <div class="flex mg-bottom-18">
        <CustomButton title="新建产品" class="mg-right-18" @click="isShowAddProductDlg=true" />
        <CustomButton title="复制产品" @click="isShowCopyProductDlg=true"></CustomButton>
      </div>
      <div class="flex-sub" v-loading="loading">
        <div class="card-list flex-warp" style="overflow-y: auto;">
          <standard-card
            v-for="value in products"
            :key="value.id"
            :switch-value="cardSwitchValue"
            class="mg-bottom-18 standard-card"
            :value="value"
            :bg-color="'color' + (parseInt(value.id[value.id.length - 1]) % 4)"
            :status2-name="cardStatus2name"
            @switch-change="handleSwitchChange"
            @visit="handleVisit"
            @del="handleDel"
          />
        </div>
      </div>
      <el-pagination
        background
        layout="prev, pager, next, total, jumper"
        :total="total"
        :page-size="formData.pageSize"
        hide-on-single-page
        @current-change="handleCurrentChange"
      />
    </div>
    <AddProductDialog :visible.sync="isShowAddProductDlg" @change="handleSearch" />
    <CopyProduct :visible.sync="isShowCopyProductDlg" @change="handleSearch" />
  </div>
</template>
<script>
import StandardCard from '@/components/standard-card/index'
import QueryContainer from '@/components/query-container'
import {
  apiFindProductPageByParam,
  apiDelProductById,
  apiUpdateProduct,
} from '@/views/device/create-product/api'
import AddProductDialog from './components/add-product.vue'
import CopyProduct from './components/copy-product'
import selectMetadata from '@/views/device/thing-model/components/selectMetadata'
import { constUtils } from '../mixin'
import CustomButton from '@/components/custom-button'

export default {
  name: 'CreateProduct',
  components: {
    StandardCard,
    CustomButton,
    AddProductDialog,
    CopyProduct,
    selectMetadata,
    QueryContainer,
  },
  mixins: [constUtils],
  data() {
    return {
      products: [],
      formData: {
        metadataId: '',
        publishStateEnum: null,
        keyword: '',
        pageNo: 1,
        pageSize: 8,
      },
      total: 0,
      loading: false,
      isShowCopyProductDlg: false,
      isShowAddProductDlg: false,
      publishStateEnum: [],
    }
  },
  computed: {
    /**
     * 卡片开关的值
     */
    cardSwitchValue() {
      return {
        activeValue: this.PublishState.PUBLICSHED,
        inactiveValue: this.PublishState.UNPUBLICSHED,
      }
    },
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.findProductPageByParam()
      this.getPublishStateEnum()
    },
    handleReset() {
      this.$refs.form.resetFields()
      this.formData = {
        metadataId: '',
        publishStateEnum: null,
        keyword: '',
        pageNo: 1,
        pageSize: 8,
      }
      this.handleSearch()
    },
    handleCurrentChange(currentPageNo) {
      this.formData.pageNo = currentPageNo
      this.findProductPageByParam()
    },
    async findProductPageByParam() {
      this.loading = true

      const { records, pageNo, pageSize, total } = await apiFindProductPageByParam(this.formData)
      this.total = total
      this.formData.pageNo = pageNo
      this.formData.pageSize = pageSize
      this.products = records.map(data => {
        return {
          ...data,
          status: data.publishState,
        }
      })
      this.loading = false
    },
    cardStatus2name(value) {
      return this.PublishStateMap[value]
    },
    async handleSearch() {
      await this.findProductPageByParam()
    },
    async handleSwitchChange(value) {
      value = {
        ...value,
        publishState: value.status,
      }
      try {
        await apiUpdateProduct(value)
        this.$message.success('更新成功')
      } catch (e) {
        this.$message.error(e)
      }
      await this.handleSearch()
    },
    handleVisit(value) {
      this.$router.push({ path: '/device/product-detail', query: { productId: value.id } })
    },
    handleDel(value) {
      apiDelProductById(value.id).then(() => {
        this.$message.success('删除成功')
        const { pageNo, pageSize } = this.formData
        const { total } = this
        if ((pageNo - 1) * pageSize >= total - 1 && pageNo > 0) {
          this.formData.pageNo--
        }
        this.handleSearch()
      })
    },
    async getPublishStateEnum() {
      this.publishStateEnum = await this.$systemEnum.getEnumByName(
        this.$CONST_ENUMS.PublishStateEnum
      )
    },
  },
}
</script>

<style scoped lang="scss">
.create-product {
  background-color: #f3f4f8;

  .content {
    padding: vw(20px);
    margin-top: vw(10px);
    background-color: white;
  }
}

.card-list {
  margin-right: vw(-20px);

  .standard-card {
    width: calc(25% - #{vw(20px)});
    margin: 0 vw(20px) vw(20px) 0;
  }
}

::v-deep .el-row--flex {
  flex-wrap: wrap;
}
</style>
